package com.atguigu.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;


/**
 * 监听MQ的消息队列，接受消息->实现自动解锁库存的功能
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 解锁库存①：下订单并锁定某商品的库存后(补偿逻辑)
     * <p>
     * 注意：只要解锁库存失败，一定要告诉RabbitMQ不要删除该消息（重新尝试解锁）
     * 手动ack
     */
    @RabbitHandler
    public void handleStockLockedRelease(Message message, StockLockedTo to, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息...");
        try {
            //尝试解锁库存
            wareSkuService.unlockStock(to);
            //解锁成功，手动ack，通知MQ删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ex) {
            //解锁失败，手动ack，拒收该消息且重新放入队列（等待下一次消费）
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 解锁库存②：订单过期且被关闭后（主要逻辑）
     */
    @RabbitHandler
    public void hanlerOrderCloseRelease(Message message, OrderTo to, Channel channel) throws IOException {
        System.out.println("收到订单关闭的消息...准备解锁库存");
        try {
            wareSkuService.unlockStock(to);
            //解锁成功，手动ack，通知MQ删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ex) {
            //解锁失败，手动ack，拒收该消息且重新放入队列（等待下一次消费）
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
